package com.pactera.madp.cp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.dto.UserInfo;
import com.pactera.madp.admin.api.feign.RemoteUserService;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.security.util.SecurityUtils;
import com.pactera.madp.cp.api.dto.activity.ActivityDto;
import com.pactera.madp.cp.api.dto.activity.ActivitySaveDto;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.activity.ActivityEntity;
import com.pactera.madp.cp.api.vo.activity.ActivityVo;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.activity.ActivityMapper;
import com.pactera.madp.cp.service.IActivityService;
import com.pactera.madp.cp.service.IWorkContactService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static java.util.Comparator.comparing;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, ActivityEntity> implements IActivityService {

    @Autowired
    private IWorkContactService workContactService;
    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public IPage queryByDto(Page page, ActivityDto dto) {
        boolean isAssessor = false;
        UserInfo userInfo = remoteUserService.info(SecurityUtils.getUser().getUsername(), SecurityConstants.FROM_IN).getData();
        String[] roleCodes = userInfo.getRoleCodes();
        for (int i=0; i<roleCodes.length; i++) {
            if (roleCodes[i].equals("ROLE_CP_AUDIT")) {
                isAssessor = true;
                break;
            }
        }
        Integer corpId = CorpContextHolder.getCorpId();
        QueryWrapper<ActivityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("corp_id", corpId);
        if (dto.getActStatus()!=null) {
            wrapper.eq("act_status", dto.getActStatus());
        } /*else {
            wrapper.eq("act_status", 0);
        }*/
        if (isAssessor) {
            wrapper.ge("act_status", 1);
            wrapper.le("act_status", 3);
        }
        if (dto.getActName()!=null && !dto.getActName().equals("")) wrapper.eq("act_name", dto.getActName());
        if (dto.getStartTime()!=null) wrapper.ge("start_time", dto.getStartTime());
        if (dto.getEndTime()!=null) wrapper.le("end_time", dto.getEndTime());
        IPage iiPage = this.page(page, wrapper);
        ArrayList<ActivityVo> list = new ArrayList<>();
        List<ActivityEntity> records = iiPage.getRecords();
        records.forEach(f -> {
            ActivityVo vo = new ActivityVo();
            BeanUtils.copyProperties(f, vo);
            Integer status = f.getActStatus();
            if (status == 0) vo.setActStatusDescribe("推审");
            if (status == 1) vo.setActStatusDescribe("待审核");
            if (status == 2) vo.setActStatusDescribe("通过");
            if (status == 3) vo.setActStatusDescribe("不通过");
            if (status == 4) vo.setActStatusDescribe("发布");
            if (status == 5) vo.setActStatusDescribe("暂停");
            list.add(vo);
        });
        list.sort(comparing(ActivityVo::getId).reversed());

        iiPage.setRecords(list);
        return iiPage;
    }

    @Override
    public Boolean compile(ActivitySaveDto dto) {
        ActivityEntity entity = new ActivityEntity();
        BeanUtils.copyProperties(dto, entity);
        if (dto.getStartTime()!=null)entity.setStartTime(dto.getStartTime().atStartOfDay());
        if (dto.getEndTime()!=null)entity.setEndTime(dto.getEndTime().atStartOfDay());
        entity.setActReason("");
        entity.setActStatus(0);
        boolean update = this.updateById(entity);
        return update;
    }

    @Override
    public Boolean audit(List<Integer> ids, Integer actStatus, String actReason) {
        if (ids != null) {
            List<ActivityEntity> list = this.lambdaQuery().in(ActivityEntity::getId, ids).list();
            list.forEach(f -> {
                UpdateWrapper<ActivityEntity> wrapper = new UpdateWrapper<>();
                if (actStatus == 1) {
                    if (f.getActStatus() == 0) {
                        wrapper.set("act_status", actStatus);
                        wrapper.eq("id", f.getId());
                        this.update(wrapper);
                    }
                } else {
                    wrapper.set("act_reason", actReason);
                    wrapper.set("act_status", actStatus);
                    wrapper.eq("id", f.getId());
                    this.update(wrapper);
                }
            });
        }
        return true;
    }

    @Override
    public R attend(Integer contactId, String url, HttpServletResponse response) {
        Integer inBlacklist = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery().eq(WorkContactEntity::getId, contactId)).getInBlacklist();
        if (inBlacklist.equals(1)) return R.failed("您是黑名单用户，无法参加该活动");
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.failed();
    }
}
